<template>
  <div>
    <a-descriptions title="费用事项"></a-descriptions>
    <a-table
      bordered
      :data-source="formList"
      :pagination="false"
      size="small"
      :rowKey="record => record.uniqueId">
      <a-table-column title="序列" key="No" data-index="No" style="width: 3%" />
      <a-table-column title="报销类目" key="applyType" data-index="applyType" style="width: 10%">
        <template slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            key="applyType"
            v-model="record.applyType"
            placeholder="请选择"
            v-if="record.editable"
          >
            <a-select-option
              v-for="item in mattersList"
              :key="item.id"
              :value="item.applyType"
              @click="getApv(item, record)"
            >
              {{ item.applyType }}
            </a-select-option>
          </a-select>
          <template v-else>
            {{ record.applyType }}
          </template>
        </template>
      </a-table-column>
      <a-table-column v-if="type===2" title="访视阶段" key="visitRecordId" data-index="visitRecordId" width="200px" >
        <template slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            placeholder="请选择"
            v-if="record.editable"
            v-model="record.visitRecordId"
            @change="(e, node) => handleVisitChange(e, node, record)"
          >
            <a-select-option v-for="item in visitList" :key="item.id" :value="item.id" :name="item.name" :stage="item.stage" >
              <span v-if="item.id > 0">{{ item.name }}:{{ item.stage }}</span>
              <span v-else>{{ item.stage }}</span>
            </a-select-option>
          </a-select>
          <template v-else>{{ record.visitRecordInfo }}</template>
        </template>
      </a-table-column>
      <a-table-column v-if="type===2" title="发生日期" key="happenDate" data-index="happenDate" >
        <template slot-scope="text, record">
          <a-date-picker v-model="record.happenDate" valueFormat="YYYY-MM-DD" v-if="record.editable" />
          <template v-else>
            <span v-if="text">{{ text | moment('YYYY-MM-DD') }}</span>
            <span v-else></span>
          </template>
        </template>
      </a-table-column>
      <a-table-column title="报销金额" key="amount" data-index="amount" >
        <template slot-scope="text, record">
          <a-input
            style="margin: -5px 0; width: 100%"
            key="amount"
            :precision="2"
            :max="999999999.99"
            :min="0"
            v-model="record.amount"
            placeholder="请输入金额"
            v-if="record.editable"
            @input="(e) => (record.amount = $commonMethods.moneyCheck(e.target.value))"
          />
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table-column>
      <a-table-column title="审批资料" key="upload" data-index="upload" style="width: 20%">
        <template slot-scope="text, record, index">
          <div v-if="record.apv == 1">
            <!-- <a-upload
              name="file"
              :multiple="true"
              action="/api/common/upload"
              :value="text"
              v-if="record.editable"
              @change="file => handleChange(file, index)"
              :showUploadList="false"
            >
              <a-button style="margin-bottom: 10px" :loading="record.loading" :disabled="record.btnSwitch"><a-icon type="upload" v-if="!record.loading" />上传</a-button>
            </a-upload> -->
            <a-button v-if="record.editable" @click="uploadFile(record, index)" :disabled="record.btnSwitch"><a-icon type="upload" />文件上传</a-button>
            <!-- <a @click="uploadFile(record, index)" v-if="record.editable">文件上传</a> -->
            <!-- <div v-if="record.editable">
              <div style="width: 100%; display: flex; justify-content: space-between" v-for="(item, index) in record.fileUrl" :key="item">
                <a :href="record.fileUrl[index] | dealImageUrl">{{ record.fileName[index] }}</a>
                <a-popconfirm title="确定删除文件？" @confirm="clickRemoveFile(record, index)">
                  <a>删除</a>
                </a-popconfirm>
              </div>
            </div> -->
            <div v-else>
              <ViewFile v-if="record.fileList.length" :data="record.fileList">
                <a>查看</a>
              </ViewFile>
              <span v-else>无</span>
            </div>
          </div>
          <div v-else>
            <span style="color: #999;">无</span>
          </div>
        </template>
      </a-table-column>
      <a-table-column v-if="type===1" title="研究者补充资料" key="supplyRemark" data-index="supplyRemark" style="width: 20%">
        <template slot-scope="text, record">
          <div v-if="record.apv == 1">
            <a-checkbox
              @change="e=>onChange1(record, e)"
              v-if="record.editable"
              style="margin-right: 5px"
              :checked="record.supply == 1"
            ></a-checkbox>
            <a-input
              style="margin: -5px 0; width:90%"
              key="supplyRemark"
              v-model="record.supplyRemark"
              placeholder="请输入备注"
              v-if="record.editable"
              :disabled="!record.btnRemarks"
            />
            <div v-else>
              {{ record.supplyRemark !== '' ? record.supplyRemark : '无' }}
            </div>
          </div>
          <div v-else>
            <span style="color: #999">无</span>
          </div>
        </template>
      </a-table-column>
      <a-table-column title="操作">
        <template slot-scope="text, record">
          <div v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record)">取消</a>
            </span>
          </div>
          <span v-else>
            <a @click="toggle(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table-column>
    </a-table>
    <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
    >新增</a-button>
    <UploadFile :uploadFileVisible="uploadFileVisible" :currentTarget="currentTarget" @closeUpload="closeUpload" ref="uploadFileRef" />
  </div>
</template>

<script>
import moment from 'moment'
import ViewFile from './researcher/ViewFile'
import UploadFile from './UploadFile'

export default {
  props: {
    type: {
      type: Number,
      required: true
    },
    mattersList: Array, // 报销类目列表
    visitList: Array // 访视阶段
  },
  components: { ViewFile, UploadFile },
  data () {
    return {
      totalAmt: 0,
      formList: [],
      loading: true,
      uploadFileVisible: false,
      currentTarget: {}
    }
  },
  methods: {
    // 打开文件上传弹窗
    uploadFile (record, i) {
      this.uploadFileVisible = true
      this.currentTarget = record
      this.$refs.uploadFileRef.copyData(record)
    },
    // 关闭文件上传
    closeUpload (info) {
      console.log(info, 'info')
      const target = this.formList.find(item => item.uniqueId === info.uniqueId)
      console.log(target, 'target')
      if (target) {
        target.fileList = info.fileList
        if (target.fileList.length) {
          target.fileUrl = target.fileList.map(item => item.fileUrl).toString()
        } else {
          target.fileUrl = ''
        }
      }
      this.uploadFileVisible = false
      this.$forceUpdate()
    },
    // 访视列表下拉改变
    handleVisitChange (value, node, record) {
      record.visitRecordId = value
      if (value > 0) {
        record.visitRecordInfo = node.data.attrs.name + ':' + node.data.attrs.stage
      } else {
        record.visitRecordInfo = node.data.attrs.stage
      }
    },
    // 保存、添加行
    saveRow (row) {
      console.log(this.type, 'type')
      const target = this.formList.find(item => item.uniqueId === row.uniqueId)
      if (!target.applyType || !target.amount) {
        this.$message.error('请将信息填写完整')
        return
      }
      if (Number(target.amount) === 0) {
        this.$message.error('报销金额不可为零')
        return
      }
      console.log(target)
      if (parseInt(target.apv) === 1) {
        // 受试者
        if (this.type !== 1 && !target.fileUrl.length) {
          console.log(target.fileUrl.length, 'length')
          this.$message.error('请上传资料')
          return false
        } else {
          // 研究者 判断上传还是补充
          if (target.btnSwitch && !target.supplyRemark) {
            this.$message.error('请输入备注信息')
            return false
          } else if (!target.fileUrl) {
            this.$message.error('请上传资料')
            return false
          }
        }
        // const boo = target.fileUrl.length || target.supplyRemark
        // if (!boo) {
        //   this.$message.error('请先将资料上传/补充完整')
        //   return false
        // }
      }
      // target.fileList = target.fileUrl.map((v, i) => {
      //   return {
      //     fileUrl: v,
      //     fileName: target.fileName[i]
      //   }
      // })
      target.isNew = false
      target.editable = false
      this.calculateCost()
      this.$emit('updateFee', this.formList, this.totalAmt)
      this.$forceUpdate()
    },
    // 计算费用
    calculateCost () {
      const arr = this.formList.filter(item => item.editable === false)
      this.totalAmt = 0
      if (arr.length > 0) {
        arr.forEach(item => {
          this.totalAmt += Number(item.amount)
        })
      }
    },
    // 上传、备注二选一
    onChange1 (record, e) {
      record.btnSwitch = !record.btnSwitch
      record.btnRemarks = !record.btnRemarks
      record.fileUrl = []
      record.fileName = []
      record.supplyRemark = ''
      record.supply = e.target.checked ? 1 : 0
      this.$forceUpdate()
    },
    // 获得当前row的apv
    getApv (item, record) {
      record.amount = item.defaulted ? item.amt : 0
      record.defaultAmt = item.amt
      record.manageCostId = item.id
      record.apv = item.apv
    },
    // 修改上传
    handleChange ({ file }, index) {
      const formList = JSON.parse(JSON.stringify(this.formList))
      formList[index].loading = true
      if (file.status === 'done') {
        if (file.response && file.response.data) {
          // 获取上传的文件的名字/路径用于展示/预览
          formList[index].fileUrl.push(file.response.data)
          formList[index].fileName.push(file.name)
          formList[index].loading = false
        } else {
          this.$message.error(file.response.detail || '上传失败')
          formList[index].loading = false
        }
      }
      this.formList = formList
    },
    // 新增行
    newMember () {
      this.formList.push({
        No: this.formList.length + 1, // No
        uniqueId: Math.random().toString().substr(2, 10), // 当前行的唯一标识
        isNew: true,
        apv: this.type === 2 ? 1 : null, // 是否审批
        applyType: null, // 报销类目
        amount: null, // 申请金额
        supplyRemark: '', // 补充说明
        editable: true, // 可修改
        manageCostId: null, // 报销类目id (费用科目接口返回的id)
        supply: 0, // 是否研究者/受试者补充资料  0:否  1:是   费用科目接口返回的apv字段决定，apv=1时开启图片上传功能
        btnSwitch: false, // 上传和补充资料二选一
        btnRemarks: false, // 上传和补充资料二选一
        fileUrl: '', // 资料地址
        fileName: [], // 资料名字
        fileList: [],
        defaultAmt: null, // 默认金额
        loading: false,
        // 受试者
        happenDate: moment().format('YYYY-MM-DD'), // 发生日期
        visitRecordId: null, // 访视记录id 访视版本下的访视记录列表id
        visitRecordInfo: null // 访视名词  访视列表返回的name
      })
      this.$emit('updateFee', this.formList, this.totalAmt)
    },
    // 编辑当前行
    toggle (record) {
      const target = this.formList.find(item => item.uniqueId === record.uniqueId)
      // 将No提取出来 因为No会动态变化
      const { No, ...targetCopy } = { ...target }
      // 因为fileName、fileUrl为数组 解构为浅拷贝 在上传文件成功后再取消操作仍会造成文件名push到fileName中,故需深拷贝
      target._originalData = JSON.parse(JSON.stringify(targetCopy))
      target.editable = !target.editable
      this.$forceUpdate()
    },
    // 取消保存当前行
    cancel (record) {
      const target = this.formList.find(item => item.uniqueId === record.uniqueId)
      // 将No提取出来 因为如果进行了删除操作，此时No已经动态变化
      const { No, ...targetCopy } = { ...target }
      Object.keys(targetCopy).forEach(item => {
        target[item] = target._originalData[item]
      })
      target._originalData = undefined
      this.$forceUpdate()
    },
    // 点击删除上传的文件
    clickRemoveFile (record, index) {
      const target = this.formList.find(item => item.uniqueId === record.uniqueId)
      target.fileUrl.splice(index, 1)
      target.fileName.splice(index, 1)
      this.$forceUpdate()
    },
    // 删除行
    remove (record) {
      const newData = this.formList.filter(item => item.uniqueId !== record.uniqueId)
      // 删除当前行后重新赋值整个表单的序列号
      for (let i = 0; i < newData.length; i++) {
        newData[i].No = i + 1
      }
      this.formList = newData
      this.calculateCost()
      this.$emit('updateFee', this.formList, this.totalAmt)
      this.$forceUpdate()
    }
  }
}
</script>
